import React, { useState, useEffect } from 'react';
import QuestionTable from './QuestionTable';
import QuestionEditModal from './QuestionEditModal';
import AIQuestionPage from './AIQuestionPage';
import ReactMarkdown from 'react-markdown';

interface MainContentProps {
  selected: string;
}

const MainContent: React.FC<MainContentProps> = ({ selected }) => {
  // 题库管理相关状态
  const [editOpen, setEditOpen] = useState(false);
  const [editQuestion, setEditQuestion] = useState<any>(null);
  const [aiPage, setAiPage] = useState(false);
  // 用于强制刷新 QuestionTable
  const [refreshFlag, setRefreshFlag] = useState(false);
  const [learningExperience, setLearningExperience] = useState('');
  const [currentPage, setCurrentPage] = useState(() => localStorage.getItem('currentPage') || '心得');

  // 读取 README.md 文件内容
  useEffect(() => {
    const fetchLearningExperience = async () => {
      try {
        const response = await fetch('/README.md');
        if (response.ok) {
          const content = await response.text();
          setLearningExperience(content);
        }
      } catch (error) {
        console.error('Failed to fetch README.md:', error);
      }
    };

    fetchLearningExperience();
  }, []);

  // 处理页面状态
  useEffect(() => {
    // 如果是首次访问，设置为学习心得页面
    if (!localStorage.getItem('currentPage')) {
      localStorage.setItem('currentPage', '心得');
      setCurrentPage('心得');
    } else {
      // 否则使用保存的页面状态
      setCurrentPage(localStorage.getItem('currentPage') || '心得');
    }
  }, []);

  // 监听页面切换
  useEffect(() => {
    if (selected) {
      localStorage.setItem('currentPage', selected);
      setCurrentPage(selected);
      // 如果切换到题库页面，检查是否在 AI 出题页面
      if (selected === '题库') {
        setAiPage(localStorage.getItem('aiPage') === 'true');
      }
    }
  }, [selected]);

  // 编辑题目
  const handleEdit = (q: any) => {
    setEditQuestion(q);
    setEditOpen(true);
  };

  // 新建题目
  const handleCreate = () => {
    setEditQuestion(null);
    setEditOpen(true);
  };

  // 保存题目
  const handleSave = async (q: any) => {
    if (q.id) {
      await fetch(`/api/questions/${q.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(q),
      });
    } else {
      await fetch('/api/questions', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(q),
      });
    }
    setEditOpen(false);
    setRefreshFlag(flag => !flag);
  };

  // 删除题目
  const handleDelete = async (ids: number[]) => {
    if (ids.length === 1) {
      await fetch(`/api/questions/${ids[0]}`, { method: 'DELETE' });
    } else if (ids.length > 1) {
      await fetch('/api/questions/batch-delete', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ids }),
      });
    }
    setRefreshFlag(flag => !flag);
  };

  // 监听"出题"下拉事件
  React.useEffect(() => {
    const manualHandler = () => handleCreate();
    const aiHandler = () => {
      setAiPage(true);
      localStorage.setItem('aiPage', 'true');
    };
    window.addEventListener('manual-create', manualHandler);
    window.addEventListener('ai-create', aiHandler);
    return () => {
      window.removeEventListener('manual-create', manualHandler);
      window.removeEventListener('ai-create', aiHandler);
    };
  }, []);

  // AI出题添加到题库
  const handleAddAIQuestions = async (qs: any[]) => {
    for (const q of qs) {
      await fetch('/api/questions', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(q),
      });
    }
    setRefreshFlag(flag => !flag);
  };

  // 处理返回题库管理
  const handleBackToQuestionTable = () => {
    setAiPage(false);
    localStorage.setItem('aiPage', 'false');
  };

  return (
    <div className="main-content">
      {currentPage === '心得' && (
        <div>
          <ReactMarkdown>{learningExperience}</ReactMarkdown>
        </div>
      )}
      {currentPage === '题库' && !aiPage && (
        <div>
          <QuestionTable onEdit={handleEdit} onDelete={handleDelete} refreshFlag={refreshFlag} />
          <QuestionEditModal
            open={editOpen}
            question={editQuestion}
            onClose={() => setEditOpen(false)}
            onSave={handleSave}
          />
        </div>
      )}
      {currentPage === '题库' && aiPage && (
        <AIQuestionPage onBack={handleBackToQuestionTable} onAdd={handleAddAIQuestions} />
      )}
    </div>
  );
};

export default MainContent;